package cc.ipost.ipost;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cc.ipost.ipost.data.RequestData;
import cc.ipost.ipost.utils.ScreenShot;

import com.umeng.analytics.MobclickAgent;

@SuppressLint({ "HandlerLeak", "HandlerLeak" })
public class AccountActivity extends Activity {
	Button login;
	Button forget;
	EditText email;
	EditText pwd;
	ProgressDialog loadingDialog;
	ViewPager mPager;
	LayoutInflater li;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		//setContentView(R.layout.login);
		setContentView(R.layout.account);
		initView();
	}
	
	public void initPager() {
		
	}

	private void initView() {
		this.li = LayoutInflater.from(this);
		View loginPage = li.inflate(R.layout.login, null);
		View signupPage = li.inflate(R.layout.signup, null);
		this.mPager = (ViewPager) findViewById(R.id.accountPagger);
		List<View> views = new ArrayList<View>();
		views.add(loginPage);
		views.add(signupPage);
		this.mPager.setAdapter(new PostViewPagerAdapter(views));
		this.mPager.setCurrentItem(0);
		
		loadingDialog = new ProgressDialog(this, R.style.MyProgressDialog);
		loadingDialog.setMessage(getString(R.string.wait_msg));
		
		// --- begin with login page
		View directToSignupBtn = loginPage.findViewById(R.id.login_right_panel);
		directToSignupBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				mPager.setCurrentItem(1);
			}
		});
		email = (EditText) loginPage.findViewById(R.id.login_email_text);
		pwd = (EditText) loginPage.findViewById(R.id.login_pwd_text);
		loginPage.findViewById(R.id.login).setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				RequestData rd = new RequestData(MySettings.LOGIN,
						RequestData.POST);
				String et = email.getText().toString();
				String pt = pwd.getText().toString();
				System.out.println(et + pt);
				if (et == null || et.length()<=0) {
					Toast.makeText(AccountActivity.this, R.string.email_field_warning,
							Toast.LENGTH_SHORT).show();
				} else if (pt == null || pt.length()<=0) {
					Toast.makeText(AccountActivity.this, R.string.pwd_field_warning,
							Toast.LENGTH_SHORT).show();
				} else {
					loadingDialog.show();
					rd.addParam("email", et);
					rd.addParam("pwd", pt);
					WebServiceTask wst = new WebServiceTask(rd, handler);
					wst.execute("");
				}
			}
		});
		loginPage.findViewById(R.id.forget_pwd).setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				String et = email.getText().toString();
				if (et == null || et.length()<=0) {
					Toast.makeText(AccountActivity.this, R.string.email_field_warning,
							Toast.LENGTH_SHORT).show();
				}else{ 
					loadingDialog.show();
					String url;
					try {
						url = MySettings.FORGETPWD+"?email="+URLEncoder.encode(et, "UTF-8");
						RequestData rd = new RequestData(url, RequestData.GET);
						WebServiceTask wst = new WebServiceTask(rd, forgetHandler);
						wst.execute("");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			}
		});
		
		// --- end of login page
		
		// --- begin with sign up page
		final EditText signEmailT = (EditText) signupPage.findViewById(R.id.signup_email_text);
		final EditText signPwdT = (EditText) signupPage.findViewById(R.id.signup_pwd_text);
		final EditText signNameT = (EditText) signupPage.findViewById(R.id.signup_name_text);
		final EditText signZipcodeT = (EditText) signupPage.findViewById(R.id.signup_zipcode_text);
		final EditText signAddressT = (EditText) signupPage.findViewById(R.id.signup_address_text);
		final EditText signPhoneT = (EditText) signupPage.findViewById(R.id.signup_phone_text);
		View signupCancelBtn = signupPage.findViewById(R.id.signup_btn_cancel);
		View signupNextBtn = signupPage.findViewById(R.id.signup_btn_next);
		signupCancelBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				mPager.setCurrentItem(0);
			}
		});
		signupNextBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				String em = signEmailT.getText().toString();
				String pwd = signPwdT.getText().toString();
				String name = signNameT.getText().toString();
				String zip = signZipcodeT.getText().toString();
				String add = signAddressT.getText().toString();
				String phone = signPhoneT.getText().toString();
				if (em.length() <= 0 || pwd.length() <= 0 || name.length() <=0 || zip.length()<=0 || add.length()<=0 || phone.length()<=0 ){
					Toast.makeText(AccountActivity.this, R.string.form_field_warning,
							Toast.LENGTH_SHORT).show();
				} else {
					RequestData rd = new RequestData(MySettings.SIGNUP,
						RequestData.POST);
					Log.i("sign up info", em + pwd + name + zip + add + phone);
					loadingDialog.show();
					rd.addParam("email", em);
					rd.addParam("pwd", pwd);
					rd.addParam("fname", name);
					rd.addParam("zipcode", zip);
					rd.addParam("location", add);
					rd.addParam("phone", phone);
					WebServiceTask wst = new WebServiceTask(rd, signHandler);
					wst.execute("");
					
				}
			}
		});
		// --- end of sign up page
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			loadingDialog.cancel();
			switch (msg.what) {
			case MySettings.FAIL: {
				Log.e("login", msg.toString());
				new AlertDialog.Builder(AccountActivity.this)
					.setMessage(msg.obj.toString())
					.setNegativeButton("OK", null)
					.setCancelable(true)
					.show();
				break;
			}
			case MySettings.ERR: {
				Log.e("login err", msg.toString());
				new AlertDialog.Builder(AccountActivity.this)
					.setMessage(msg.obj.toString())
					.setNegativeButton("OK", null)
					.setCancelable(true)
					.show();
				break;
			}
			case MySettings.SUCCESS: {
				Log.e("login success", msg.toString());
				try {
					JSONObject user = ((JSONObject) msg.obj).getJSONObject("user");
					MyApplication ma = (MyApplication) getApplication();
					ma.initUser(user);
					Intent i = new Intent(AccountActivity.this, MainActivity.class);
					i.putExtra("reload", false);
					startActivity(i);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				System.out.println(msg.obj);
			}
			}

		}
	};
	private Handler forgetHandler = new Handler() {
		public void handleMessage(Message msg) {
			loadingDialog.cancel();
			switch (msg.what) {
			case MySettings.FAIL: {
				Log.e("forget", msg.toString());
				String msgs = "Something went wrong, please try again later.";
				if (msg != null && msg.obj != null) {
					msgs = msg.obj.toString();
				}
				new AlertDialog.Builder(AccountActivity.this)
						.setMessage(msgs).setNegativeButton("OK", null)
						.setCancelable(true).show();
				break;
			}
			case MySettings.ERR: {
				Log.e("forget err", msg.toString());
				new AlertDialog.Builder(AccountActivity.this)
					.setMessage(msg.obj.toString())
					.setNegativeButton("OK", null)
					.setCancelable(true)
					.show();
				break;
			}
			case MySettings.SUCCESS: {
				Log.e("forget success", msg.toString());
					new AlertDialog.Builder(AccountActivity.this)
					.setMessage("We sent a email to you. Check it!")
					.setNegativeButton("OK", null)
					.setCancelable(true)
					.show();
			}
			}

		}
	};

	private Handler signHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MySettings.FAIL: {
				Log.e("sign", msg.toString());
				break;
			}
			case MySettings.ERR: {
				loadingDialog.dismiss();
				Log.e("sign err", msg.toString());
				new AlertDialog.Builder(AccountActivity.this)
					.setMessage(msg.obj.toString())
					.setNegativeButton("OK", null)
					.setCancelable(true)
					.show();
				break;
			}
			case MySettings.SUCCESS: {
				loadingDialog.cancel();
				Log.e("sign success", msg.toString());
				try {
					JSONObject user = ((JSONObject) msg.obj).getJSONObject("user");
					MyApplication ma = (MyApplication) getApplication();
					ma.initUser(user);
					Intent i = new Intent(AccountActivity.this, MainActivity.class);
					i.putExtra("reload", false);
					startActivity(i);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				System.out.println(msg.obj);
			}
			}

		}
	};
	
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_MENU) {
			ScreenShot.shoot(this);
		}
		return super.onKeyDown(keyCode, event);
	}
}
